package com.lanou3g.demo;

import com.google.gson.Gson;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Main1 {
    public static void main(String[] args) throws DocumentException, IOException {
        SAXReader reader = new SAXReader();
        Document xml = reader.read("output.xml");
        Gson gson = new Gson();
        List<Snack> snacks = new ArrayList<>();

        Element rootElement = xml.getRootElement();

        Iterator<Element> iterator = rootElement.elementIterator();

        while (iterator.hasNext()) {
            Element next = iterator.next();
            String id = next.elementText("id");
            String name = next.elementText("name");
            String price = next.elementText("price");
            String quantity = next.elementText("quantity");
            String unit = next.elementText("unit");

            Snack snack1 = new Snack();
            snack1.setId(Integer.parseInt(id));
            snack1.setName(name);
            snack1.setPrice(Double.valueOf(price));
            snack1.setQuantity(Integer.parseInt(quantity));
            snack1.setUnit(unit);

            snacks.add(snack1);
        }

        String s = gson.toJson(snacks);
        Writer w = new FileWriter("output.json");
        w.write(s);
        w.flush();
        w.close();
    }
}
